<template>
  <el-dialog
    v-model="dialogFormVisible"
    title="附件"
    width="45%"
    @close="close"
    append-to-body
  >
    <el-upload
      multiple
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      class="upload-file-uploader"
      ref="fileUpload"
      v-if="showButton"
    >
      <el-button size="mini" type="primary">选取文件</el-button>
    </el-upload>

    <!-- 文件列表 -->
    <el-table
      ref="fileTable"
      :data="fileList"
      :maxHeight="300"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column
        label="文件名"
        prop="name"
        sortable
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span class="el-icon-document">
            {{ row?.name || row?.fileName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" sortable show-overflow-tooltip>
        <template #default="scoped">
          <el-link
            :underline="false"
            @click="handleDownLoad(scoped.row)"
            type="primary"
            style="margin-right: 15px"
            >下载</el-link
          >
          <el-link
            :underline="false"
            @click="handleDelete(scoped.$index)"
            type="danger"
            >删除</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <template #footer v-if="showButton">
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="onSubmit"> 确 认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import { downLoadFile } from "@/api/common";
export default {
  name: "FileUpload",
  props: {
    // 数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf", "docx", "xlsx"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    title: String,
    showButton: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: import.meta.env.VITE_APP_BASE_API,
      uploadFileUrl: import.meta.env.VITE_APP_BASE_API + "/file/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      dialogFormVisible: false,
    };
  },
  watch: {},
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      if (this.limit <= this.fileList.length) {
        this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
        return false;
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.closeLoading();
      this.number--;
      this.$modal.msgError("上传文件失败，请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.$modal.closeLoading();
        this.uploadList.push({
          name: res.data.fileName,
          url: res.data.fileUrl,
          id: res.data.id,
        });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
    },
    // 上传结束处理
    uploadedSuccessfully() {
      console.log(this.number);
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$modal.closeLoading();
      }
    },
    close() {
      this.dialogFormVisible = false;
    },
    open(files) {
      this.dialogFormVisible = true;
      let list = files || [];
      this.$nextTick().then(() => {
        this.fileList = list.filter((item) => item != null);
      });
    },
    onSubmit() {
      this.$emit("onSubmit", this.fileList);
    },
    handleDownLoad(row) {
      downLoadFile(row?.url, row.name);
    },
  },
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
